package com.example.messagemodule.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.constants.ProjectConfigure;
import com.examination.mlib.constants.UserInfoConstants;
import com.examination.mlib.customview.AppTitleBar;
import com.examination.mlib.db.DataBaseUtil;
import com.examination.mlib.manager.LocalNotificatioManager;
import com.examination.mlib.manager.PermissionManager;
import com.examination.mlib.view.preview.PreviewBuilder;
import com.example.messagemodule.MessageNet;
import com.example.messagemodule.R;
import com.example.messagemodule.adapter.ConversationMessageAdapter;
import com.example.messagemodule.adapter.ConversationMoreAdapter;
import com.example.messagemodule.adapter.SelectAdapter;
import com.example.messagemodule.constants.ConversationMoreConstants;
import com.example.messagemodule.entity.ChargeEntity;
import com.example.messagemodule.entity.ConversationMore;
import com.example.messagemodule.entity.DoctorWorkTabEntity;
import com.example.messagemodule.entity.EntryGroupEntity;
import com.example.messagemodule.entity.EntryImEntity;
import com.example.messagemodule.entity.HbasePatientImManagerEntity;
import com.example.messagemodule.entity.ImagesListBean;
import com.example.messagemodule.entity.SelectEntity;
import com.example.messagemodule.entity.TalkEntity;
import com.example.messagemodule.listener.EventBusMessageWrap;
import com.example.messagemodule.listener.IMSendMessageListener;
import com.example.messagemodule.manager.MessageType;
import com.example.messagemodule.manager.TestImageLoader;
import com.example.messagemodule.utils.MessageUtils;
import com.example.messagemodule.widget.AppointmentPicWaitView;
import com.example.messagemodule.widget.ConversationInputView;
import com.example.messagemodule.widget.InquiryHintView;
import com.example.messagemodule.widget.InquiryStatusView;
import com.example.messagemodule.widget.InquiryWaitView;
import com.example.messagemodule.widget.TalkingButton;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCursorResult;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.luck.picture.lib.compress.Luban;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.ZoomMediaLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shicheng.mediaplayer.AudioSensorBinder;
import com.shicheng.mediaplayer.media.MediaCallBack;
import com.shicheng.mediaplayer.media.MediaManager;
import com.examination.mlib.baseold.ModuleBaseActivity;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ActivityManagerUtils;
import com.yilijk.base.utils.BitmapUtils;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.CommonUtils;
import com.yilijk.base.utils.DataUtils;
import com.yilijk.base.utils.DevicesUtils;
import com.yilijk.base.utils.KeyboardUtils;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import crossoverone.statuslib.StatusUtil;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static androidx.core.content.FileProvider.getUriForFile;
import static com.examination.mlib.constants.AllStringConstants.recall;
import static com.examination.mlib.constants.AllStringConstants.recallGruop;
import static com.examination.mlib.constants.ProjectConfigure.debugFun;

@Route(path = ARouterConstants.ConversationActivity)
public class ConversationActivity extends ModuleBaseActivity implements LifecycleOwner {

    /**
     * 数据库表明 存储未编辑完输入框内容
     */
    private static final String DB_FN_CONVER_INPUT = "converInput";

    //LifecycleRegistry 实现了Lifecycle
    LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(ConversationActivity.this);
    AudioSensorBinder audioSensorBinder;

    private LinearLayout convetsationUpload;
    private TextView convetsationUploadOption1;
    private TextView convetsationUploadOption2;
    private CardView conversationSelecte;
    private CardView convetsationSelectOption1;
    private CardView convetsationSelectOption2;
    private ArrayList<SelectEntity> selectData = new ArrayList<>();
    private SelectAdapter selectAdapter;
    private static final int REQUEST_CODE = 0x00000012;
    private static final int REQUEST_CODE2 = 0x00000013;
    private static final int CAMERA_CODE = 0x00000014;


//    private ImageView conversationChangeVoiceInput;
//    private EditText conversationInputEt;
//    private TalkingButton conversationVoiceBt;
//    private ImageView convetsationShowMore;
    private RecyclerView conversationMore;
//    private TextView conversationSendMessage;
    private boolean isShowVoice = false;
    private boolean isShowMore = false;
    private SmartRefreshLayout conversationMessageSmart;
    private ArrayList<HbasePatientImManagerEntity.DataBean> conversationMessages = new ArrayList<>();
    private RecyclerView conversationMessage;
    private ConversationMessageAdapter conversationMessageAdapter;
    private LinearLayout conversationAgainDescription;
    private PopupWindow editPopwindow;
    private View editPopWindowView;
    private TextView editPopwindowCopy;
    private TextView editPopwindowReport;
    //    private TextView editPopwindowCut;
    private TextView editPopwindowRecall;
    private int conversationLongClickPosition = -1;
    private int conversationClickLastPosition = -1;
    //    private MediaPlayer voicePlayer = new MediaPlayer();
    private boolean isToTextSuccess = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };
    private int canSendMessageNo = 0;
    //接收传递值
    @Autowired
    public long doctorPassportId;
    @Autowired
    public int chargesListId;
    //    @Autowired
//    public long doctorId;
    @Autowired
    public boolean isInquiryRecord;
    @Autowired
    public int chatTypeStatus;
    @Autowired
    public String externalOrderNo;
    /*
     * 0 Chat  单聊
     * 1 GroupChat   群聊
     * 2 ChatRoom    聊天室
     */

    public EntryImEntity.DataBean entryData;
    public EntryGroupEntity.DataBean entryGroupData;
    private String currentMsgId;
    private float X;
    private float Y;
    private AnimationDrawable animationDrawableLeft = null;
    private AnimationDrawable animationDrawableRight = null;

    //进入im请求参数
    private int status = -1;
    private boolean isWaitting = false;
    private boolean isEnd = false;
    private boolean isUploadImage = false;
    private int type = -1;
    private String chargesCreateTime = "";
    private String chargesVisitTime = "";
    private File outputImage;
    private Uri imageUri;
    private String imagePath;
    AppTitleBar appTitleBar;
    //存储已经评价完成的chargesListIds
    private ArrayList<Integer> chargesListIds = new ArrayList<Integer>();

    //电话问诊
    private LinearLayout phoneTime;
    private TextView phoneTimeContent;

    private TextView contentSign;
    private CardView closeSign;

    private RelativeLayout sign;

    InquiryHintView inquirtHintView;

    long lastSendTime = 0;

    InquiryWaitView inquiryWaitView;
    AppointmentPicWaitView appointmentPicWaitView;
    InquiryStatusView inquiryStatusView;
    ConversationInputView conversationInputView;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ALog.e("setMessageType   oakkkkkkk");
            if (intent != null) {
                if ("RN_KIT_BROADCAST_NATIVE_NAME_001".equals(intent.getAction())) {
                    String tag = "";
                    String pageName = "";
                    String content = intent.getStringExtra("RN_KIT_BROADCAST_NATIVE_CONTENT");
                    String filterName = intent.getStringExtra("RN_KIT_BROADCAST_NATIVE_FILTER_NAME");

                    ALog.e("setMessageType content: " + content);
                    ALog.e("setMessageType name: " + filterName);
                    if (!TextUtils.isEmpty(content) && "ReceiveRefreshKey".equals(filterName)) {
                        try {
                            JSONObject jsonObject = new JSONObject(content);
                            tag = jsonObject.getString("tag");
                            pageName = jsonObject.getString("pageName");
                            ALog.e("setMessageType tag: " + tag + " pageName: " + pageName);
                            /**
                             * 关闭评价 刷新页面
                             */
                            if ("ThanksDetail".equals(pageName)) {
//                                chargeEntities.clear();
                                initData();
                            }

                        } catch (Throwable throwable) {
                            if (debugFun) {
                                throwable.printStackTrace();
                                ALog.e("setMessageType throwable: " + throwable.getMessage());
                            }
                        }
                    }

                }
            }
        }
    };


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //低音监听
        audioSensorBinder = new AudioSensorBinder(this);
        mLifecycleRegistry.addObserver(audioSensorBinder);

        IntentFilter filter = new IntentFilter("RN_KIT_BROADCAST_NATIVE_NAME_001");
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
    }

    @Override
    public int bondLayout() {
        return R.layout.activity_conversation;
    }

    static {
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.color_F4F4F4, android.R.color.black);//全局设置主题颜色
                ClassicsHeader.REFRESH_HEADER_REFRESHING = "正在加载";//正在加载
                ClassicsHeader.REFRESH_HEADER_RELEASE = "释放加载更多";//释放加载更多
                ClassicsHeader.REFRESH_HEADER_PULLING = "下拉加载";//下拉加载
                ClassicsHeader.REFRESH_HEADER_FAILED = "加载失败";//加载失败
                ClassicsHeader.REFRESH_HEADER_UPDATE = "上次加载 M-d HH:mm";//加载失败
                ClassicsHeader.REFRESH_HEADER_FINISH = "加载完毕";//加载失败
                ClassicsHeader classicsHeader = new ClassicsHeader(context);
                return classicsHeader;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        //设置全局的Header构建器
        StatusUtil.setSystemStatus(this, false, true);
        StatusUtil.setUseStatusBarColor(this, Color.WHITE);
        //键盘顶掉布局
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //更多点击item
         appTitleBar = findViewById(R.id.titleBar);
        //历史消息
        conversationMessage = (RecyclerView) findViewById(R.id.conversation_message);
        //历史消息上拉下拉
        conversationMessageSmart = (SmartRefreshLayout) findViewById(R.id.conversation_message_smart);
        if (isInquiryRecord) {
            conversationMessageSmart.setEnableRefresh(false);
        } else {
            conversationMessageSmart.setEnableRefresh(true);
        }
        //设置 Footer 为 球脉冲 样式
        conversationMessageSmart.setRefreshFooter(new BallPulseFooter(this).setSpinnerStyle(SpinnerStyle.Scale));
        //关闭上拉加载
        conversationMessageSmart.setEnableLoadMore(false);
        //再次咨询
        conversationAgainDescription = (LinearLayout) findViewById(R.id.conversation_again_description);
        //上传图片——模板消息
        convetsationUpload = (LinearLayout) findViewById(R.id.convetsation_upload);
//        暂时没有
        convetsationUploadOption1 = (TextView) findViewById(R.id.convetsation_upload_option1);
//        上传图片
        convetsationUploadOption2 = (TextView) findViewById(R.id.convetsation_upload_option2);
//        选项-模板消息
        conversationSelecte = (CardView) findViewById(R.id.conversation_selecte);
//        item父类
        RecyclerView selecteItemParent = (RecyclerView) findViewById(R.id.selecte_item_parent);

        inquirtHintView = findViewById(R.id.inquity_hint_v);
        inquiryWaitView = findViewById(R.id.inquiry_wait_view);
        appointmentPicWaitView = findViewById(R.id.appointment_pic_wait_v);
        inquiryStatusView = findViewById(R.id.inquiry_status_view);
        conversationInputView = findViewById(R.id.conversation_input_v);

        convetsationSelectOption1 = (CardView) findViewById(R.id.convetsation_select_option1);
        convetsationSelectOption2 = (CardView) findViewById(R.id.convetsation_select_option2);


        convetsationSelectOption1 = (CardView) findViewById(R.id.convetsation_select_option1);
        convetsationSelectOption2 = (CardView) findViewById(R.id.convetsation_select_option2);

        FixGridLayout fixGridLayout = new FixGridLayout();
        fixGridLayout.setAutoMeasureEnabled(true);
        selecteItemParent.setLayoutManager(fixGridLayout);
        selectAdapter = new SelectAdapter(selectData);
        selecteItemParent.setAdapter(selectAdapter);
        selectAdapter.notifyDataSetChanged();
        conversationMessageAdapter = new ConversationMessageAdapter(conversationMessages);
        conversationMessage.setLayoutManager(new LinearLayoutManager(this));
        conversationMessage.setAdapter(conversationMessageAdapter);
        notifyDataSetChanged();

        contentSign = (TextView) findViewById(R.id.content_sign);
        closeSign = (CardView) findViewById(R.id.close_sign);
        sign = (RelativeLayout) findViewById(R.id.sign);

        phoneTime = (LinearLayout) findViewById(R.id.phone_time);
        phoneTimeContent = (TextView) findViewById(R.id.phone_time_content);

        //长按弹出窗体
        initEditPopWindow();
    }


    @Override
    public void initData() {
        if (getIntent() != null) {
            try {
                Intent intent = getIntent();
                ALog.e(intent.toString());
                doctorPassportId = Long.parseLong(intent.getStringExtra("doctorPassportId"));
            } catch (Exception e) {

            }
        }
//        charge赋值


        LoadingUtils.getLoadingUtils(this).showLoading();
        if (chatTypeStatus == 0) {
            entryIm(true);
            findViewById(R.id.fast_button_ll).setVisibility(View.GONE);
        } else if (chatTypeStatus == 1) {
            appTitleBar.setTitle("复诊开方");
            //默认展示输入框
            conversationInputView.setCanSendMsg(true);
            //隐藏带接诊倒计时、结束问诊模板、最后模板消息、电话问诊、模板选项
            conversationAgainDescription.setVisibility(View.GONE);
            convetsationUpload.setVisibility(View.GONE);
            phoneTime.setVisibility(View.GONE);
            conversationSelecte.setVisibility(View.GONE);
            entryGroup(externalOrderNo);
            ClickUtils.setFastOnClickListener(findViewById(R.id.fast_button_send_pic), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PermissionManager.getInstance()
                            .get(ConversationActivity.this)
                            .requestPermissions(
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}
                                    ,
                                    new String[]{"允许应用使用文件存储权限", "允许应用使用文件访问权限"})
                            .requestCodes(0xa1)
                            .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
                                @Override
                                public void noM() {

                                }

                                @Override
                                public void granted() {
                                    //上传图片
                                    ImageSelector.builder()
                                            .useCamera(true) // 设置是否使用拍照
                                            .setSingle(false)  //设置是否单选
                                            .canPreview(true) //是否点击放大图片查看,，默认为true
                                            .setMaxSelectCount(9) // 图片的最大选择数量，小于等于0时，不限数量。
                                            .start(ConversationActivity.this, REQUEST_CODE); // 打开相册
                                }

                                @Override
                                public void denied() {

                                }
                            })
                            .request();
                }
            });
        }


    }


    @Override
    public void initEvent() {

        conversationInputView.setInputViewClickListener(new ConversationInputView.InputViewClickListener() {
            @Override
            public void sendTXTmsg(String txtString) {
                EMMessage txtSendMessage = EMMessage.createTxtSendMessage(txtString, getCurrentToAccount());
                sendEMMessage(getChatType(), txtSendMessage, false);
                removeInputText();
            }

            @Override
            public void sendVOICEmsg(String path, int length) {
                EMMessage voiceSendMessage = EMMessage.createVoiceSendMessage(path, length, getCurrentToAccount());
                sendEMMessage(getChatType(), voiceSendMessage, false);
            }

            @Override
            public void refreshPosition() {
                conversationMessage.scrollToPosition(conversationMessages.size() - 1);
            }

            @Override
            public void adapterCarame() {
                        PermissionManager.getInstance()
                                .get(ConversationActivity.this)
                                .requestPermissions(
                                        new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}
                                        ,
                                        new String[]{"允许应用使用相机权限", "允许应用使用文件存储权限"})
                                .requestCodes(0xa1)
                                .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
                                    @Override
                                    public void noM() {

                                    }

                                    @Override
                                    public void granted() {
                                        //拍摄
                                        String state = Environment.getExternalStorageState();
                                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                                            String path = Environment.getExternalStorageDirectory().getPath();
                                            //创建拍摄图片的目录
                                            File file = new File(path + "/Pictures/");
                                            if (!file.exists()) {
                                                if (!file.mkdirs()) {
                                                    //目录创建失败
                                                }
                                            }
                                            imagePath = file.getAbsolutePath() + "/" + "h1tx" + System.currentTimeMillis() + ".jpg";
                                            outputImage = new File(imagePath);
//拍照后原图回存入此路径
                                            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                                                imageUri = Uri.fromFile(outputImage);
                                            } else {
                                                //7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider
                                                imageUri = getUriForFile(ConversationActivity.this, "com.ylkj.patient.fileprovider", outputImage);
                                            }
                                            //启动相机拍照
                                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                            startActivityForResult(intent, CAMERA_CODE);
                                        }
                                    }

                                    @Override
                                    public void denied() {

                                    }
                                })
                                .request();
            }

            @Override
            public void adapterImage() {
                        PermissionManager.getInstance()
                                .get(ConversationActivity.this)
                                .requestPermissions(
                                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}
                                        ,
                                        new String[]{"允许应用使用文件存储权限", "允许应用使用文件访问权限"})
                                .requestCodes(0xa1)
                                .setmRequestPermissionCallBack(new PermissionManager.RequestPermissionCallBack() {
                                    @Override
                                    public void noM() {

                                    }

                                    @Override
                                    public void granted() {
                                        //上传图片
                                        ImageSelector.builder()
                                                .useCamera(true) // 设置是否使用拍照
                                                .setSingle(false)  //设置是否单选
                                                .canPreview(true) //是否点击放大图片查看,，默认为true
                                                .setMaxSelectCount(
                                                        getChatType() == EMMessage.ChatType.Chat ?
                                                                entryData.getImChargesList().getType() == 8 ? canSendMessageNo : 9
                                                                :
                                                                entryGroupData.getImTeamChargesList().getType() == 8 ? canSendMessageNo : 9

                                                ) // 图片的最大选择数量，小于等于0时，不限数量。
                                                .start(ConversationActivity.this, REQUEST_CODE); // 打开相册
                                    }

                                    @Override
                                    public void denied() {

                                    }
                                })
                                .request();

            }
        });

        inquiryStatusView.setOnInquiryStatusComplent(new InquiryStatusView.OnInquiryStatusComplent() {
            @Override
            public void waiting() {
                if (getChatType() == EMMessage.ChatType.Chat) {
                    if (entryData.getImChargesList().getType() == 4 || entryData.getImChargesList().getType() == 7) {
                        phoneTime.setVisibility(View.VISIBLE);
                        phoneTimeContent.setText("医生预计于" +
                                entryData.getImChargesList().getRelevantDateStr() +
                                entryData.getImChargesList().getStartTime() +
                                "至" +
                                entryData.getImChargesList().getEndTime() +
                                "接诊，医生均在临床一线工作，接诊时间可能稍延迟，请您耐心等待。");
                    } else if (entryData.getImChargesList().getType() == 3) {

                    } else {
                        //设置等待时间
                        inquiryWaitView.setCreatTime(chargesCreateTime);
                    }
                } else if (getChatType() == EMMessage.ChatType.GroupChat) {
//                设置等待时间
                }
            }

            @Override
            public void noWaiting() {
                inquiryWaitView.destoryView();
            }

            @Override
            public void ending() {
                conversationInputView.setCanSendMsg(false);
            }

            @Override
            public void noEnding() {
                conversationInputView.setCanSendMsg(true);
            }

            @Override
            public void finishInquiry() {
                conversationInputView.setCanSendMsg(false);
                entryIm(true);
            }

            @Override
            public void refreshAppointmentPicWait() {
                if (entryData != null && entryData.getImChargesList() != null) {
                    EntryImEntity.DataBean.ImChargesListBean imChargesList = entryData.getImChargesList();
                    appointmentPicWaitView
                            .setData(
                                    imChargesList.getRelevantDateStr(),
                                    Integer.parseInt(imChargesList.getWeekNum()),
                                    imChargesList.getStartTime(),
                                    imChargesList.getEndTime()
                            );
                }
            }

            @Override
            public void refreshInquiryEndHint(String chargeStatus) {
                setShowInquiryEndHint(chargeStatus);
            }

            @Override
            public void refreshChargeUi(int status) {
                setChargeUI(3);
            }
        });

        inquirtHintView.setInquiryHintClickListener(new InquiryHintView.InquiryHintClickListener() {
            @Override
            public void clickAdapter(int position) {
                Bundle bundle = new Bundle();
                bundle.putString("doctorId", doctorPassportId + "");
                switch (position) {
                    case 0:
                        bundle.putInt("jumpStudioType", 1);
                        bundle.putInt("selectIndex", 1);
                        break;
                    case 1:
                        bundle.putInt("jumpStudioType", 3);
                        bundle.putInt("selectIndex", 1);
                        break;
                    case 2:
                        bundle.putInt("jumpStudioType", 4);
                        bundle.putInt("selectIndex", 1);
                        break;
                    case 3:
                        bundle.putInt("jumpStudioType", 0);
                        bundle.putInt("selectIndex", 0);
                        break;
                }
                MessageUtils.push(ConversationActivity.this,
                        KitArouterConstants.IM_DOCTORBUNDLE,
                        KitArouterConstants.Message.DoctorStudio,
                        bundle);
            }
        });
        //关闭
        ClickUtils.setFastOnClickListener(closeSign, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sign.setVisibility(View.GONE);
            }
        });
        //上传图片
        ClickUtils.setFastOnClickListener(convetsationUploadOption2, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上传图片
                ImageSelector.builder()
                        .useCamera(true) // 设置是否使用拍照
                        .setSingle(false)  //设置是否单选
                        .canPreview(true) //是否点击放大图片查看,，默认为true
                        .start(ConversationActivity.this, REQUEST_CODE2); // 打开相册
            }
        });
        //暂时没有
        ClickUtils.setFastOnClickListener(convetsationUploadOption1, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EMMessage txtSendMessage = EMMessage.createTxtSendMessage("暂时没有", getCurrentToAccount());
                sendEMMessage(getChatType(), txtSendMessage, false);
                conversationInputView.setCanSendMsg(true);
                convetsationUpload.setVisibility(View.GONE);
            }
        });
        //确定
        ClickUtils.setFastOnClickListener(convetsationSelectOption2, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //确定
                String content = "";
                for (int i = 0; i < selectData.size(); i++) {
                    if (selectData.get(i).isSelect()) {
                        content = content + "\t" + selectData.get(i).getTitle();
                    }
                }
                if (!content.equals("") && !content.isEmpty() && content != null) {
                    EMMessage txtSendMessage = EMMessage.createTxtSendMessage(content, getCurrentToAccount());
                    sendEMMessage(getChatType(), txtSendMessage, false);
                    convetsationSelectOption2.setAlpha(0.5f);
                    conversationInputView.setCanSendMsg(true);
                    conversationSelecte.setVisibility(View.GONE);
                }
            }
        });
        //不清楚
        ClickUtils.setFastOnClickListener(convetsationSelectOption1, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //不清楚
                EMMessage txtSendMessage = EMMessage.createTxtSendMessage("不清楚", getCurrentToAccount());
                sendEMMessage(getChatType(), txtSendMessage, false);
                conversationInputView.setCanSendMsg(true);
                conversationSelecte.setVisibility(View.GONE);
            }
        });

        ClickUtils.setAdapterItemFastOnClickListener(selectAdapter, new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == selectData.size() - 1) {
                    selectData.get(position).setSelect(true);
                    for (int i = 0; i < selectData.size() - 1; i++) {
                        selectData.get(i).setSelect(false);
                    }
                } else {
                    selectData.get(selectData.size() - 1).setSelect(false);
                    if (selectData.get(position).isSelect()) {
                        selectData.get(position).setSelect(false);
                    } else {
                        selectData.get(position).setSelect(true);
                    }
                }
                selectAdapter.notifyDataSetChanged();
                for (int i = 0; i < selectData.size(); i++) {
                    if (selectData.get(i).isSelect()) {
                        convetsationSelectOption2.setAlpha(1.0f);
                        break;
                    } else {
                        convetsationSelectOption2.setAlpha(0.5f);
                    }
                }
            }
        });
        //刷新监听
        conversationMessageSmart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (getChatType() == EMMessage.ChatType.Chat) {
                    getConversationHistory();
                } else if (getChatType() == EMMessage.ChatType.GroupChat) {
                    conversationMessageSmart.finishRefresh();
//                    conversationMessageSmart.setEnableRefresh(false);
                }
            }
        });
        //复制点击
        ClickUtils.setFastOnClickListener(editPopwindowCopy, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (conversationMessages.get(conversationLongClickPosition).getEmMessage() == null) {
                    String msgType = conversationMessages.get(conversationLongClickPosition).getMsgType();
                    if ("txt".equals(msgType)) {
                        String content = conversationMessages.get(conversationLongClickPosition).getContent();
                        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clipData = ClipData.newPlainText("message", content);
                        clipboardManager.setPrimaryClip(clipData);
                        Toast.makeText(ConversationActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    EMMessage emMessage = conversationMessages.get(conversationLongClickPosition).getEmMessage();
                    if (emMessage.getType() == EMMessage.Type.TXT) {
                        EMTextMessageBody emTextMessageBody = (EMTextMessageBody) emMessage.getBody();
                        String message = emTextMessageBody.getMessage();
                        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clipData = ClipData.newPlainText("message", message);
                        clipboardManager.setPrimaryClip(clipData);
                        Toast.makeText(ConversationActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ConversationActivity.this, "无法复制非文本信息", Toast.LENGTH_SHORT).show();
                    }
                }
                editPopwindow.dismiss();
            }
        });
        //撤销
        ClickUtils.setFastOnClickListener(editPopwindowRecall, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EMMessage emMessage = null;

                if (conversationMessages.get(conversationLongClickPosition).getEmMessage() == null) {
                    String msgId = null;
                    if (conversationLongClickPosition + 1 == conversationMessages.size()) {
                        msgId = null;
                    } else {
                        msgId = conversationMessages.get(conversationLongClickPosition + 1).getMsgId();
                    }
                    try {
                        EMCursorResult<EMMessage> emMessageEMCursorResult = EMClient.getInstance().chatManager().fetchHistoryMessages(getCurrentToAccount(), EMConversation.EMConversationType.Chat, 1, msgId);
                        if (emMessageEMCursorResult != null && emMessageEMCursorResult.getData() != null) {
                            if (emMessageEMCursorResult.getData().size() > 0) {
                                emMessage = emMessageEMCursorResult.getData().get(0);
                            }
                        }
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }

                } else {
                    emMessage = conversationMessages.get(conversationLongClickPosition).getEmMessage();
                }
                if (emMessage != null) {
                    EMMessage finalEmMessage = emMessage;
                    EMClient.getInstance().chatManager().aysncRecallMessage(emMessage, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            //发送一条本地撤销消息
                            EMMessage sendMessage = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
                            EMCustomMessageBody customMessageBody = new EMCustomMessageBody("recall");
                            HashMap<String, String> hashMap = new HashMap<>();
                            hashMap.put("content", "您撤回了一条消息");
                            customMessageBody.setParams(hashMap);
                            sendMessage.setBody(customMessageBody);
                            sendMessage.setTo(getCurrentToAccount());
                            HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                            dataBean.setEmMessage(sendMessage);
                            conversationMessages.add(dataBean);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    conversationMessages.remove(conversationLongClickPosition);
                                    notifyDataSetChanged();
                                }
                            });
                            RequestParams jsonObject = new RequestParams();
                            if (getChatType() == EMMessage.ChatType.Chat) {
                                jsonObject.put("chargesListId", entryData.getImChargesList().getChargesListId());
                            } else if (getChatType() == EMMessage.ChatType.GroupChat) {
                                jsonObject.put("chargesListId", entryGroupData.getChargesListId());
                            }
                            jsonObject.put("msgId", finalEmMessage.getMsgId());
                            if (chatTypeStatus == 0) {
                                HttpUtils.post(recall, jsonObject, new HttpCallBack<Object>() {
                                    @Override
                                    public void onSuccess(Object o, int i) {

                                    }

                                    @Override
                                    public void onFailure(String s, int i) {

                                    }
                                });
                            } else if (chatTypeStatus == 1) {
                                HttpUtils.post(recallGruop, jsonObject, new HttpCallBack<Object>() {
                                    @Override
                                    public void onSuccess(Object o, int i) {

                                    }

                                    @Override
                                    public void onFailure(String s, int i) {

                                    }
                                });
                            }
                        }

                        @Override
                        public void onError(int code, String error) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ConversationActivity.this, "撤回失败，超过3分钟的消息无法撤回", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        @Override
                        public void onProgress(int progress, String status) {

                        }
                    });
                }
                editPopwindow.dismiss();
            }
        });
        //举报
        ClickUtils.setFastOnClickListener(editPopwindowReport, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(ARouterConstants.ContractWebviewActivity)
                        .withString("title", "在线客服")
                        .withBoolean("isShowLoading", true).navigation();
            }
        });
        //消息长按
        conversationMessageAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                editPopwindowCopy.setVisibility(View.GONE);
//                editPopwindowCut.setVisibility(View.GONE);
                editPopwindowReport.setVisibility(View.GONE);
                editPopwindowRecall.setVisibility(View.GONE);
                conversationLongClickPosition = position;
                View viewByPosition = conversationMessage.getLayoutManager().findViewByPosition(position);

//                EMMessage.Type type = conversationMessages.get(position).getEmMessage().getType();
                int itemViewType = conversationMessages.get(position).getItemType();
                View viewById = null;
                long msgTime = 0;
                if (conversationMessages.get(position).getEmMessage() == null) {
                    msgTime = Long.valueOf(DataUtils.string2long(conversationMessages.get(position).getSendTime(), "yyyy-MM-ss HH:mm:ss")).longValue();
                } else {
                    msgTime = conversationMessages.get(position).getEmMessage().getMsgTime();
                }
                switch (itemViewType) {
                    case MessageType
                            .LEFT.MessageType_TXT:
                        editPopwindowReport.setVisibility(View.VISIBLE);
                        editPopwindowCopy.setVisibility(View.VISIBLE);
                        viewById = viewByPosition.findViewById(R.id.message_text_left_content);
                        break;
                    case MessageType
                            .RIGHT.MessageType_TXT:
                        if (isLongtoTime(msgTime)) {
                            editPopwindowRecall.setVisibility(View.VISIBLE);
                        }
                        editPopwindowCopy.setVisibility(View.VISIBLE);
                        viewById = viewByPosition.findViewById(R.id.message_text_right_content);
                        break;
                    case MessageType
                            .LEFT.MessageType_IMAGE:
                        editPopwindowReport.setVisibility(View.VISIBLE);
                        viewById = viewByPosition.findViewById(R.id.message_image_left_content);
                        break;
                    case MessageType
                            .RIGHT.MessageType_IMAGE:
                        if (isLongtoTime(msgTime)) {
                            editPopwindowRecall.setVisibility(View.VISIBLE);
                        }
                        viewById = viewByPosition.findViewById(R.id.message_image_right_content);
                        break;
                    case MessageType
                            .LEFT.MessageType_AUDIO:
                        editPopwindowReport.setVisibility(View.VISIBLE);
                        viewById = viewByPosition.findViewById(R.id.message_voice_left_content);
                        break;
                    case MessageType
                            .RIGHT.MessageType_AUDIO:
                        if (isLongtoTime(msgTime)) {
                            editPopwindowRecall.setVisibility(View.VISIBLE);
                        }
                        viewById = viewByPosition.findViewById(R.id.message_voice_right_content);
                        break;
                    default:
                        return false;
                }
                showEditPopWindow(viewById);
                return false;
            }
        });

        conversationMessageAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int itemViewType = conversationMessages.get(position).getItemType();
                if (itemViewType == MessageType.LEFT.MessageType_IMAGE && view.getId() == R.id.message_image_left_content ||
                        itemViewType == MessageType.RIGHT.MessageType_IMAGE && view.getId() == R.id.message_image_right_content){
                    messageOfImgClick(position, view);
                }else if (itemViewType == MessageType.LEFT.MessageType_AUDIO && view.getId() == R.id.message_voice_left_content ||
                        itemViewType == MessageType.RIGHT.MessageType_AUDIO && view.getId() == R.id.message_voice_right_content){
                    messageOfVoiceClick(position);
                }
                conversationClickLastPosition = position;
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        ClickUtils.sendEvent(ClickApi.Message.page_ConversationShow, this, "聊天详情载入");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!EMClient.getInstance().isLoggedInBefore()) {
            String imAccount = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imAccount, null);
            String imPassword = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imPassword, null);
            if (imAccount != null && imPassword != null) {
                EMClient.getInstance().login(imAccount, imPassword, new EMCallBack() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError(int code, String error) {

                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }
                });
            } else {
                boolean b = SharedPreferencesUtils.getInstance().removeAll();
                if (b) {
                    ARouter.getInstance().build(ARouterConstants.CenterActivity).navigation();
                    ActivityManagerUtils.finishAllActivity();
                }
            }
        }
    }

    @Override
    public void finish() {
        KeyboardUtils.closeKeybord(this);
        super.finish();
    }

    /**
     * 页面销毁
     */
    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);

//        if (voicePlayer.isPlaying()) {
//            voicePlayer.stop();
//            voicePlayer = null;
//        }
        MediaManager.removeAll();
        if (ConversationMessageAdapter.chargesIds != null) {
            ConversationMessageAdapter.chargesIds.clear();
        }
        mLifecycleRegistry.removeObserver(audioSensorBinder);
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        super.onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            // 结果回调
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
//                  boolean isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
            ALog.d("ImageSelector", "是否是拍照图片：" + images.get(0));
            Flowable.just(images)
                    .observeOn(Schedulers.io())
                    .map(list -> {
                        @SuppressLint("CheckResult") List<File> files =
                                Luban.with(this)
                                        .load(list)
                                        .setTargetDir(this.getExternalCacheDir().getAbsolutePath())
                                        .ignoreBy(100)
                                        .get();
                        if (files == null) {
                            files = new ArrayList<>();
                        }
                        return files;
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<File>>() {
                        @Override
                        public void accept(List<File> files) throws Exception {
                            String[] uris = new String[files.size()];
                            for (int i = 0; i < files.size(); i++) {
                                ALog.d("imagePath", "onActivityResult: " + files.get(i).getPath());
                                String path = files.get(i).getPath();
                                Uri pa = Uri.fromFile(new File(path));//根据路径转化为uri
                                ALog.d("imagePath", "onActivityResult: " + pa.toString());
                                uris[i] = path;
                                EMMessage imageSendMessage = EMMessage.createImageSendMessage(path, false, getCurrentToAccount());
                                imageSendMessage.setMessageStatusCallback(new IMSendMessageListener(imageSendMessage));
                                sendEMMessage(getChatType(), imageSendMessage, false);
                            }

                        }
                    });
        } else if (requestCode == REQUEST_CODE2 && data != null) {
            // 结果回调
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
//                  boolean isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
            ALog.d("ImageSelector", "是否是拍照图片：" + images.get(0));
            Flowable.just(images)
                    .observeOn(Schedulers.io())
                    .map(list -> {
                        @SuppressLint("CheckResult") List<File> files =
                                Luban.with(this)
                                        .load(list)
                                        .setTargetDir(this.getExternalCacheDir().getAbsolutePath())
                                        .ignoreBy(100)
                                        .get();
                        if (files == null) {
                            files = new ArrayList<>();
                        }
                        return files;
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<List<File>>() {
                        @Override
                        public void accept(List<File> files) throws Exception {
                            String[] uris = new String[files.size()];
                            for (int i = 0; i < files.size(); i++) {
                                String path = files.get(i).getPath();
                                Uri pa = Uri.fromFile(new File(path));//根据路径转化为uri
                                uris[i] = path;
                            }
                            sendLastImg(uris, 0);
                        }
                    });
        } else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
//                    CAMERA_CODE
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                BitmapUtils.saveBitmap(bitmap, imagePath);
                EMMessage imageSendMessage = EMMessage.createImageSendMessage(imagePath, false, getCurrentToAccount());
                imageSendMessage.setMessageStatusCallback(new IMSendMessageListener(imageSendMessage));
                sendEMMessage(getChatType(), imageSendMessage, false);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }


    }


    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  //把操作放在用户点击的时候

            /**
             * 此时可能点击的事件不止一个点，多点触摸，比如两个以上手指同时触摸屏幕。
             *
             */
            for (int i = 0; i < event.getPointerCount(); i++) {
                float x = event.getX(i);
                float y = event.getY(i);
                if (KeyboardUtils.touchEventInView(conversationInputView.getSendView(), x, y)) {

                } else if (!KeyboardUtils.touchEventInView(conversationInputView.getInputView(), x, y)) {
                    KeyboardUtils.closeKeybord(this);   //收起键盘
                } else if (KeyboardUtils.touchEventInView(conversationInputView.getInputView(), x, y)) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            notifyDataSetChanged();
                        }
                    }, 200);
                }

            }
//            View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
//            if (v!=null){
//                ALog.e("dispatchTouchEvent",v.getId()+"");
//            }

        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 消息内容语音点击
     *
     * @param position
     */
    void messageOfVoiceClick(int position) {
        if (conversationMessages.get(position).getEmMessage() == null) {
            HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(position);
            String attach = dataBean.getAttach();
            String url = "";
            int length = 0;
            try {
                JSONObject jsonObject = new JSONObject(attach);
                if (jsonObject.has("url")) {
                    url = jsonObject.getString("url");
                }
                if (jsonObject.has("length")) {
                    length = jsonObject.getInt("length");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            long l = DataUtils.string2long(dataBean.getSendTime(), "yyyy-MM-dd HH:mm:ss");

            try {
                playVoice(url, length, position, l);
            } catch (Throwable t) {

            }
        } else {
            EMMessage emMessage = conversationMessages.get(position).getEmMessage();
            EMVoiceMessageBody voiceMessageBody1 = (EMVoiceMessageBody) emMessage.getBody();
            ALog.e(emMessage.getMsgTime() + "");
            try {
                playVoice(voiceMessageBody1.getRemoteUrl(), voiceMessageBody1.getLength(), position, emMessage.getMsgTime());
            } catch (Throwable t) {

            }
        }
    }

    /**
     * 消息内容图片点击时间
     *
     * @param position
     */
    void messageOfImgClick(int position, View view) {
        int index = 0;
        if (conversationMessages.get(position).getEmMessage() == null) {
            HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(position);
            String fileUrl = dataBean.getFileUrl();
            ArrayList<ImagesListBean> images = new ArrayList<>();
            for (int i = 0; i < conversationMessages.size(); i++) {
                if (conversationMessages.get(i).getEmMessage() == null) {
                    if ("img".equals(conversationMessages.get(i).getMsgType())) {
                        ImagesListBean imagesListBean = new ImagesListBean(conversationMessages.get(i).getFileUrl());
                        images.add(imagesListBean);
                    }
                    if (fileUrl.equals(conversationMessages.get(i).getFileUrl())) {
                        index = images.size() - 1;
                    }
                } else {
                    if (conversationMessages.get(i).getEmMessage().getType() == EMMessage.Type.IMAGE) {
                        EMImageMessageBody body = (EMImageMessageBody) conversationMessages.get(i).getEmMessage().getBody();
                        String remoteUrl = body.getRemoteUrl();
                        ImagesListBean imagesListBean = new ImagesListBean(remoteUrl);
                        images.add(imagesListBean);
                    }

                }

            }
            PreviewBuilder.from(ConversationActivity.this).setData(images)
                    .setCurrentIndex(index)
                    .setSingleFling(true)
                    .setDrag(true)
                    .setType(PreviewBuilder.IndicatorType.Number)
                    .start(view);
        } else {
            EMImageMessageBody imageBody = (EMImageMessageBody) conversationMessages.get(position).getEmMessage().getBody();
            String remoteUrl = imageBody.getRemoteUrl();
            List<ImagesListBean> images = new ArrayList<>();
            for (int i = 0; i < conversationMessages.size(); i++) {
                if (conversationMessages.get(i).getEmMessage() == null) {
                    if ("img".equals(conversationMessages.get(i).getMsgType())) {
                        ImagesListBean imagesListBean = new ImagesListBean(conversationMessages.get(i).getFileUrl());
                        images.add(imagesListBean);
                    }
                } else {
                    if (conversationMessages.get(i).getEmMessage().getType() == EMMessage.Type.IMAGE) {
                        EMImageMessageBody body = (EMImageMessageBody) conversationMessages.get(i).getEmMessage().getBody();
                        String imgurl = body.getRemoteUrl();
                        ImagesListBean imagesListBean = new ImagesListBean(imgurl);
                        images.add(imagesListBean);
                        if (remoteUrl.equals(imgurl)) {
                            index = images.size() - 1;
                        }
                    }

                }

            }
            GPreviewBuilder.from(ConversationActivity.this).setData(images)
                    .setCurrentIndex(index)
                    .setSingleFling(true)
                    .setDrag(true)
                    .setType(GPreviewBuilder.IndicatorType.Number)
                    .start();
        }
    }

    /**
     * 发生图片模板最后
     */
    void sendLastImg(String[] uris, int index) {
        EMMessage imageSendMessage = EMMessage.createImageSendMessage(uris[index++], false, getCurrentToAccount());
        int finalIndex = index;
        imageSendMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                dataBean.setEmMessage(imageSendMessage);
                conversationMessages.add(dataBean);
                notifyDataSetChanged();
                sendLastImg(uris, finalIndex);
            }

            @Override
            public void onError(int code, String error) {

            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
        boolean isLast = false;
        if (index == uris.length) {
            isLast = true;
        } else {
            isLast = false;
        }
        HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(conversationMessages.size() - 1);
        try {
            if (dataBean.getEmMessage() == null) {
                String ext = dataBean.getExt();
                Map<String, Object> extMap = (Map<String, Object>) JSON.parse(ext);
                MessageUtils.setExt(imageSendMessage, extMap, isLast);
            } else {
                MessageUtils.setExt(imageSendMessage, dataBean.getEmMessage().ext(), isLast);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        imageSendMessage.setChatType(getChatType());
        ALog.i("cus", "sendEMMessage: " + imageSendMessage.ext());
        EMClient.getInstance().chatManager().sendMessage(imageSendMessage);

    }

    /**
     * 语音播放
     *
     * @param urlString
     * @param length
     * @param position
     */
    void playVoice(String urlString, int length, int position, long sendTime) {
        String url = "";
        if (length == 0) {
            ToastUtils.showShort("播放错误");
            return;
        }
        if (sendTime == 0) {
            ToastUtils.showShort("播放错误");
            return;
        } else {
            if (System.currentTimeMillis() - sendTime > 24 * 60 * 60 * 1000) {
                url = changeUrlVoide(urlString);
            } else {
                url = urlString;
            }
        }
        View viewByPosition = conversationMessage.getLayoutManager().findViewByPosition(position);
        ImageView voiceImageViewLeft = viewByPosition.findViewById(R.id.message_voice_left_icon);
        ImageView voiceImageViewRight = viewByPosition.findViewById(R.id.message_voice_right_icon);
        //判断上一次 跟这次播放是否是同一个语音  不是同一个语音 结束上一个 同时改变UI刷新状态
        if (MediaManager.isPlaying() && position != conversationClickLastPosition && conversationClickLastPosition != -1) {
            View viewByPositionLast = conversationMessage.getLayoutManager().findViewByPosition(conversationClickLastPosition);
            HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(conversationClickLastPosition);
            int itemType = dataBean.getItemType();
            if (itemType == 5000) {
                if (animationDrawableLeft != null) {
                    animationDrawableLeft.stop();
                    animationDrawableLeft = null;
                }
                if (viewByPositionLast != null) {
                    ImageView voiceImageViewLeftLast = viewByPositionLast.findViewById(R.id.message_voice_left_icon);
                    voiceImageViewLeftLast.setBackground(getResources().getDrawable(R.drawable.voice_left_playing));
                }
                ImageView voiceImageViewLeftLast = viewByPositionLast.findViewById(R.id.message_voice_left_icon);
                voiceImageViewLeftLast.setBackground(getResources().getDrawable(R.drawable.voice_left_playing));
//                Glide.with(this).load(R.drawable.voice_left_playing).into(voiceImageViewLeftLast);
            } else if (itemType == 5001) {
                if (animationDrawableRight != null) {
                    animationDrawableRight.stop();
                    animationDrawableRight = null;
                }
                if (viewByPositionLast != null) {
                    ImageView voiceImageViewRightLast = viewByPositionLast.findViewById(R.id.message_voice_right_icon);
                    voiceImageViewRightLast.setBackground(getResources().getDrawable(R.drawable.voice_right_playing));
                }
//                Glide.with(this).load(R.drawable.voice_right_playing).into(voiceImageViewRightLast);
            }
//            if (voicePlayer != null) {
//                voicePlayer.stop();
//            }
//            voicePlayer = null;
            MediaManager.stop();
        }
        int voiceType = conversationMessages.get(position).getItemType();
        if (MediaManager.isPlaying()) {
            MediaManager.stop();
        } else {
//            ToastUtils.make().setBgColor(getResources().getColor(R.color.color_99000000))
//                    .setTextColor(getResources().getColor(R.color.white))
//                    .show("播放中，如无声音请打开手机静音");
            MediaManager.builder()
                    .setContext(this)
                    .setAudioManager(audioSensorBinder.getAudioManager(false))
                    .setUrl(url)
                    .setOpenToast(true)
                    .setToastContext("播放中，如无声音请打开手机静音")
                    .setDebugModel(DevicesUtils.isEnvironment())
                    .setMediaListener(new MediaCallBack() {
                        @Override
                        public void progress(int i, int max) {

                        }

                        @Override
                        public void prepare(int duration, String time) {
                            MediaManager.start();
                        }

                        @Override
                        public void start() {
                            //ui更新
                            if (voiceType == 5000) {
                                animationDrawableLeft = (AnimationDrawable) voiceImageViewLeft.getBackground();
                                animationDrawableLeft.start();
//                    Glide.with(this).load(R.drawable.message_voice_left_playing).into(voiceImageViewLeft);
                            } else if (voiceType == 5001) {
                                animationDrawableRight = (AnimationDrawable) voiceImageViewRight.getBackground();
                                animationDrawableRight.start();
//                    Glide.with(this).load(R.drawable.message_voice_right_playing).into(voiceImageViewRight);
                            }
                        }

                        @Override
                        public void pause() {

                        }

                        @Override
                        public void stop() {
                            //ui更新
                            if (voiceType == 5000) {
                                animationDrawableLeft = (AnimationDrawable) voiceImageViewLeft.getBackground();
                                animationDrawableLeft.stop();
                                animationDrawableLeft = null;
                                voiceImageViewLeft.setBackground(getResources().getDrawable(R.drawable.voice_left_playing));
//                    Glide.with(this).load(R.drawable.message_voice_left_playing).into(voiceImageViewLeft);
                            } else if (voiceType == 5001) {
                                animationDrawableRight = (AnimationDrawable) voiceImageViewRight.getBackground();
                                animationDrawableRight.stop();
                                animationDrawableRight = null;
                                voiceImageViewRight.setBackground(getResources().getDrawable(R.drawable.voice_right_playing));
//                    Glide.with(this).load(R.drawable.message_voice_right_playing).into(voiceImageViewRight);
                            }
                        }

                        @Override
                        public void completion() {

                            if (voiceType == 5000) {
                                if (animationDrawableLeft != null) {
                                    animationDrawableLeft.stop();
                                    animationDrawableLeft = null;
                                }
                                voiceImageViewLeft.setBackground(getResources().getDrawable(R.drawable.voice_left_playing));
//                        Glide.with(ConversationActivity.this).load(R.drawable.message_voice_left).transform(new CenterCrop()).into(voiceImageViewLeft);
                            } else if (voiceType == 5001) {
                                if (animationDrawableRight != null) {
                                    animationDrawableRight.stop();
                                    animationDrawableRight = null;
                                }
                                voiceImageViewRight.setBackground(getResources().getDrawable(R.drawable.voice_right_playing));
//                        Glide.with(ConversationActivity.this).load(R.drawable.message_voice_right).into(voiceImageViewRight);
                            }

                        }

                        @Override
                        public void error() {
                            ToastUtils.make().setBgColor(getResources().getColor(R.color.color_99000000))
                                    .setTextColor(getResources().getColor(R.color.white))
                                    .show("语音播放出错");
                        }
                    })
                    .build();

        }

    }

    //初始化eidtpopwindow
    void initEditPopWindow() {
        editPopwindow = new PopupWindow();
        editPopWindowView = getLayoutInflater().inflate(R.layout.message_edit_popwindow, null);
        editPopwindowCopy = (TextView) editPopWindowView.findViewById(R.id.edit_popwindow_copy);
        editPopwindowRecall = (TextView) editPopWindowView.findViewById(R.id.edit_popwindow_recall);
//        editPopwindowCut = (TextView) editPopWindowView.findViewById(R.id.edit_popwindow_cut);
        editPopwindowReport = (TextView) editPopWindowView.findViewById(R.id.edit_popwindow_report);

        editPopwindow.setOutsideTouchable(true);
        editPopwindow.setFocusable(true);
        editPopwindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        editPopwindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        editPopwindow.setContentView(editPopWindowView);
    }

    //长按弹出popwindow
    void showEditPopWindow(View view) {
        int i = view.getWidth() / 2 - 70;
        editPopwindow.showAsDropDown(view, i, 0 - view.getHeight() - 100, Gravity.LEFT);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    //设置问诊页面状态
    void setChargeUI(int status) {
        inquiryWaitView.destoryView();
        conversationAgainDescription.setVisibility(View.GONE);
//        conversationInputView.setVisibility(View.GONE);
        phoneTime.setVisibility(View.GONE);
        if (getChatType() == EMMessage.ChatType.Chat) {
            inquiryStatusView.refreshStatus(entryData);
        } else {
            inquiryStatusView.refreshStatus(entryGroupData);
        }


    }

    //发送消息
    void sendEMMessage(EMMessage.ChatType type, EMMessage emMessage, boolean isLast) {
        if (conversationMessages.size() > 0) {
            HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(conversationMessages.size() - 1);
            try {
                if (dataBean.getEmMessage() == null) {
                    String ext = dataBean.getExt();
                    ALog.i("cus", "sendEMMessage: " + ext);
                    Map<String, Object> extMap = (Map<String, Object>) JSON.parse(ext);
                    MessageUtils.setExt(emMessage, extMap, isLast);
                } else {
                    Map<String, Object> ext1 = dataBean.getEmMessage().ext();
                    String ext = dataBean.getEmMessage().ext().toString();
                    ALog.i("cus", "sendEMMessage: " + ext);
                    MessageUtils.setExt(emMessage, dataBean.getEmMessage().ext(), isLast);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Map<String, Object> extMap = (Map<String, Object>) JSON.parse(new Gson().toJson(entryGroupData));
            try {
                MessageUtils.setExt(emMessage, extMap, isLast);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        emMessage.setChatType(type);
        if (ProjectConfigure.Open.isOpenUnlinePush) {
            // 强制推送
            emMessage.setAttribute("em_force_notification", true);
            ALog.i("cus", "sendEMMessage: " + emMessage.ext());
            emMessage.setTo("6006");
// 设置自定义推送提示
            JSONObject extObject = new JSONObject();
            try {
                extObject.put("em_push_name", "离线推送标题");
                extObject.put("em_push_content", "离线推送内容部分");
            } catch (JSONException e) {
                e.printStackTrace();
            }
// 将推送扩展设置到消息中
            emMessage.setAttribute("em_apns_ext", extObject);
        }
        emMessage.setMessageStatusCallback(new IMSendMessageListener(emMessage));
        EMClient.getInstance().chatManager().sendMessage(emMessage);
    }

    /*
     * 进去群组聊天
     *
     * */
    private void entryGroup(String externalOrderNo) {
        RequestParams params = new RequestParams();
        params.put("chargesListId", externalOrderNo);
        HttpUtils.get(AllStringConstants.MessageUrl.queryChargesImTeam, params, new HttpCallBack<EntryGroupEntity>() {
            @Override
            public void onSuccess(EntryGroupEntity entryGroupEntity, int code) {
                if (entryGroupEntity.isResult()) {
                    entryGroupData = entryGroupEntity.getData();
                    openImChargeByChargeListId(entryGroupData.getChargesListId());
                    if (entryGroupData.getImTeamChargesList() != null && entryGroupData.getImTeamChargesList().isCanConsulting()) {
                        status = entryGroupData.getImTeamChargesList().getChargesListStatus();
                        chargesCreateTime = entryGroupData.getImTeamChargesList().getChargesCreateTime();
                        chargesVisitTime = entryGroupData.getImTeamChargesList().getChargesVisitTime();
                        type = entryGroupData.getImTeamChargesList().getType();
                        conversationInputView.setCanSendMsg(true);
                    } else {
                        conversationInputView.setCanSendMsg(false);
                    }
                    if (entryGroupData.isHasKjhf()) {
                        findViewById(R.id.fast_button_ll).setVisibility(View.VISIBLE);
                    } else {
                        findViewById(R.id.fast_button_ll).setVisibility(View.GONE);
                    }
                    conversationMessages.clear();
                    if (entryGroupData.getImTeamChargesList() != null) {
                        setChargeUI(entryGroupData.getImTeamChargesList().getChargesListStatus());
                        //显示问诊状态
                        inquiryStatusView.setVisibility(View.VISIBLE);
                    }
                    if (entryGroupEntity.getData() != null && entryGroupEntity.getData().getImRecords() != null) {
                        for (int i = 0; i < entryGroupEntity.getData().getImRecords().size(); i++) {
                            EntryGroupEntity.DataBean.ImRecordsBean imRecordsBean = entryGroupEntity.getData().getImRecords().get(i);
                            HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                            if (imRecordsBean != null) {
                                if (imRecordsBean.getImTeamId() != null) {
                                    dataBean.setImTeamId(imRecordsBean.getImTeamId());
                                }
                                if (imRecordsBean.getMsgId() != null) {
                                    dataBean.setMsgId(imRecordsBean.getMsgId());
                                }
                                if (imRecordsBean.getFromAccount() != null) {
                                    dataBean.setFromAccount(imRecordsBean.getFromAccount());
                                }
                                if (imRecordsBean.getToAccount() != null) {
                                    dataBean.setToAccount(imRecordsBean.getToAccount());
                                }
                                if (imRecordsBean.getMsgType() != null) {
                                    dataBean.setMsgType(imRecordsBean.getMsgType());
                                }
                                if (imRecordsBean.getChargesListId() != 0) {
                                    dataBean.setChargesListId(imRecordsBean.getChargesListId());
                                }
                                if (imRecordsBean.getSendTime() != null) {
                                    dataBean.setSendTime(imRecordsBean.getSendTime());
                                }
                                if (imRecordsBean.getContent() != null) {
                                    dataBean.setContent(imRecordsBean.getContent());
                                }
                                if (imRecordsBean.getFileUrl() != null) {
                                    dataBean.setFileUrl(imRecordsBean.getFileUrl());
                                }
                                if (imRecordsBean.getCustomEvent() != null) {
                                    dataBean.setCustomEvent(imRecordsBean.getCustomEvent());
                                }
                                if (imRecordsBean.getCustomExt() != null) {
                                    dataBean.setCustomExt(imRecordsBean.getCustomExt());
                                }
                                if (imRecordsBean.getAttach() != null) {
                                    dataBean.setAttach(imRecordsBean.getAttach());
                                }
                                if (imRecordsBean.getExt() != null) {
                                    dataBean.setExt(imRecordsBean.getExt());
                                }
                            }
                            conversationMessages.add(dataBean);
                        }
                    }
                    notifyDataSetChanged();
                }

            }

            @Override
            public void onFailure(String s, int i) {


            }
        });
    }
    //进入im页面
    void entryIm(boolean isEntry) {
        MessageNet.entryIm(this, doctorPassportId, new HttpCallBack<EntryImEntity>() {
            @Override
            public void onSuccess(EntryImEntity entryImEntity, int i) {
                if (entryImEntity.isResult() && entryImEntity.getData() != null) {
                    EntryImEntity.DataBean data = entryImEntity.getData();
                    openImChargeByChargeListId(data.getImChargesList().getChargesListId());
                    entryData = data;
                    getInputText();
                    conversationMessageAdapter.callPhone = entryData.getImChargesList().getCallPhone();
                    status = data.getImChargesList().getChargesListStatus();
                    chargesCreateTime = data.getImChargesList().getChargesCreateTime();
                    chargesVisitTime = data.getImChargesList().getChargesVisitTime();
                    type = data.getImChargesList().getType();
                    if (type == 8) {
                        queryResidueDegree();
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (isInquiryRecord) {
                                appTitleBar.setTitle("问诊记录");
                                ConversationMessageAdapter.isInquiryRecord = true;
                                inquiryStatusView.setVisibility(View.GONE);
                                setChargeUI(-1);
                            } else {
                                appTitleBar.setTitle(entryData.getImChargesList().getDoctorName());
                                ConversationMessageAdapter.isInquiryRecord = false;

                                inquiryStatusView.setVisibility(View.VISIBLE);
                                setChargeUI(status);
                            }
                            if (isEntry) {
                                getMsgRecordFromServer();
                            }
                        }
                    });
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ConversationActivity.this, "" + entryImEntity.getMsg(), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }
    //从服务器拉取消息
    void getMsgRecordFromServer() {
        RequestParams jsonObject = new RequestParams();
        if (isInquiryRecord) {
            jsonObject.put("chargesListid", chargesListId);
        } else {
            jsonObject.put("chargesListid", entryData.getImChargesList().getChargesListId());
        }
        HttpUtils.get(AllStringConstants.easemobImManager, jsonObject, new HttpCallBack<HbasePatientImManagerEntity>() {
            @Override
            public void onSuccess(HbasePatientImManagerEntity hbasePatientImManagerEntity, int i) {
                if (hbasePatientImManagerEntity.isResult()) {
                    conversationMessages.clear();
                    conversationMessages.addAll(hbasePatientImManagerEntity.getData());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            notifyDataSetChanged();

                        }
                    });
                } else {
                    Toast.makeText(ConversationActivity.this, "" + hbasePatientImManagerEntity.getMsg(), Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

    void queryResidueDegree() {
        RequestParams queryResidueDegreeparams = new RequestParams();
        queryResidueDegreeparams.put("chargesListId", entryData.getImChargesList().getChargesListId());
        HttpUtils.get(AllStringConstants.MessageUrl.queryResidueDegree, queryResidueDegreeparams, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {
                ALog.e(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("result") && jsonObject.getBoolean("result")) {
                        canSendMessageNo = jsonObject.getInt("data");
                        conversationInputView.setInputHint("剩余回复条数：" + canSendMessageNo);
                        if (canSendMessageNo == 0) {
                            conversationInputView.forbiddenInput(false);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

    /**
     * 下拉刷新
     */
    void getConversationHistory() {
        if (conversationMessages == null || conversationMessages.size() < 0) {
            conversationMessageSmart.finishRefresh();
            return;
        }
        long msgId = 0;
        if (conversationMessages.size() == 0) {
            msgId = entryData.getImChargesList().getChargesListId();
        } else {
            msgId = conversationMessages.get(0).getChargesListId();
        }
        RequestParams jsonObject = new RequestParams();
        jsonObject.put("chargesListid", msgId);
        HttpUtils.get(AllStringConstants.historyPatientMsg, jsonObject, new HttpCallBack<HbasePatientImManagerEntity>() {
            @Override
            public void onSuccess(HbasePatientImManagerEntity hbasePatientImManagerEntity, int i) {
                if (hbasePatientImManagerEntity.isResult()) {
                    conversationMessages.addAll(0, hbasePatientImManagerEntity.getData());
                    notifyDataSetChanged(hbasePatientImManagerEntity.getData().size());
                    conversationMessageSmart.finishRefresh();
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

    /**
     * 设置消息类型
     */
    void setMessageType() {
        if (ConversationMessageAdapter.chargesIds != null) {
            ConversationMessageAdapter.chargesIds.clear();
        }
        for (int i = 0; i < conversationMessages.size(); i++) {
            HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(i);
            //设置双方头像
            if (getChatType() == EMMessage.ChatType.Chat) {
                dataBean.setFromAvator(entryData.getImChargesList().getDoctorImageUrl() == null ?
                        CommonUtils.imageTranslateUri(this, R.drawable.default_head)
                        :
                        entryData.getImChargesList().getDoctorImageUrl());
                dataBean.setSelfAvator(entryData.getPatientImageUrl() == null ?
                        CommonUtils.imageTranslateUri(this, R.drawable.default_head)
                        :
                        entryData.getPatientImageUrl());
            } else if (getChatType() == EMMessage.ChatType.GroupChat) {
                dataBean.setFromAvator(CommonUtils.imageTranslateUri(this, R.drawable.group_head));
                if (entryGroupData.getImTeamChargesList() != null && !TextUtils.isEmpty(entryGroupData.getImTeamChargesList().getPatientImage())) {
                    dataBean.setSelfAvator(entryGroupData.getImTeamChargesList().getPatientImage());
                } else {
                    dataBean.setSelfAvator(CommonUtils.imageTranslateUri(this, R.drawable.default_head));
                }
            }
            dataBean.setChatType(getChatType());
            //私有化服务器消息
            if (dataBean.getEmMessage() == null) {
               MessageUtils.disposeHbaseMessage(dataBean,getCurrentFromAccount());
            } else {
                MessageUtils.disposeEMMessage(dataBean,getCurrentFromAccount());
            }
            disposeMsgTime(dataBean);
        }
    }

    /**
     * 刷新聊天内容
     */

    void notifyDataSetChanged() {
        notifyDataSetChanged(-1);
    }

    void notifyDataSetChanged(int position) {
        if (ProjectConfigure.Open.isOpenNotification) {
            if (chatTypeStatus == 0) {
                LocalNotificatioManager.getInstance(this).cancelNotification(this, entryData.getImChargesList().getChargesListId());
            } else if (chatTypeStatus == 1) {
                LocalNotificatioManager.getInstance(this).cancelNotification(this, entryGroupData.getChargesListId());
            }
        }
        if (conversationMessageAdapter != null && entryData != null) {
            conversationMessageAdapter.setStartTime_description(entryData.getImChargesList().getStartTime());
            conversationMessageAdapter.setEndTime_description(entryData.getImChargesList().getEndTime());
            conversationMessageAdapter.setRelevantDateStr(entryData.getImChargesList().getRelevantDateStr());
        }
        LoadingUtils.getLoadingUtils(this).dismissLoading();
        setMessageType();
        if (isInquiryRecord && conversationMessages.size() > 0) {
            HbasePatientImManagerEntity.DataBean dataBean_start = new HbasePatientImManagerEntity.DataBean();
            EMMessage txtSendMessage_start = EMMessage.createTxtSendMessage("开始时间: " + conversationMessages.get(0).getSendTime(), entryData.getPatientImAccount());
            dataBean_start.setType(999);
            dataBean_start.setEmMessage(txtSendMessage_start);
            conversationMessages.add(0, dataBean_start);
            HbasePatientImManagerEntity.DataBean dataBean_end = new HbasePatientImManagerEntity.DataBean();
            EMMessage txtSendMessage_end = EMMessage.createTxtSendMessage("结束时间: " + conversationMessages.get(conversationMessages.size() - 1).getSendTime(), entryData.getPatientImAccount());
            dataBean_end.setType(-999);
            dataBean_end.setEmMessage(txtSendMessage_end);
            conversationMessages.add(dataBean_end);
        }
        if (getChatType() == EMMessage.ChatType.Chat){
            conversationInputView.setCanSendMsg(entryData != null && entryData.isCanSendMsg());
            conversationInputView.setShortCurButton(entryData != null && entryData.isHasKjhf());
        }

        conversationMessageAdapter.notifyDataSetChanged();
        if (position >= 0){
            conversationMessage.scrollToPosition(position);
        }else{
            conversationMessage.scrollToPosition(conversationMessages.size() - 1);
        }
        if (conversationMessages == null || conversationMessages.size() <= 0) {
            return;
        }

        HbasePatientImManagerEntity.DataBean dataBean = conversationMessages.get(conversationMessages.size() - 1);
        if (dataBean.getEmMessage() == null) {
            if (dataBean.getFromAccount().equals(getCurrentToAccount())) {
                if ("last_charges_template".equals(dataBean.getCustomEvent())) {
                    convetsationUpload.setVisibility(View.GONE);
                    conversationInputView.setCanSendMsg(true);
                }
                String ext = dataBean.getExt();
                try {
                    JSONObject jsonObject = new JSONObject(ext);
                    if (jsonObject.has("templateExt")) {
                        JSONObject templateExt = jsonObject.getJSONObject("templateExt");
                        if (templateExt.has("inputType")) {
                            String inputType = templateExt.getString("inputType");
                            if ("checkbox".equals(inputType)) {
                                if (templateExt.has("optionsStr")) {
                                    JSONArray optionsStr = templateExt.getJSONArray("optionsStr");
                                    selectData.clear();
                                    for (int i = 0; i < optionsStr.length(); i++) {
                                        String string = optionsStr.getString(i);
                                        selectData.add(new SelectEntity(string, false));
                                    }
                                    selectAdapter.notifyDataSetChanged();
                                    conversationSelecte.setVisibility(View.VISIBLE);
                                    KeyboardUtils.closeKeybord(ConversationActivity.this);

                                    conversationInputView.setCanSendMsg(false);
                                }
                            } else if ("pic".equals(inputType)) {
                                convetsationUpload.setVisibility(View.VISIBLE);
                                conversationInputView.setCanSendMsg(true);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (dataBean.getEmMessage().getFrom().equals(getCurrentToAccount())) {
                EMMessage emMessage = dataBean.getEmMessage();
                if (emMessage.getType() == EMMessage.Type.CUSTOM) {
                    EMCustomMessageBody body = (EMCustomMessageBody) emMessage.getBody();
                    if ("last_charges_template".equals(body.event())) {
                        convetsationUpload.setVisibility(View.GONE);
                        conversationInputView.setCanSendMsg(true);
                    }
                }
                Map<String, Object> ext = emMessage.ext();
                String templateExt = (String) ext.get("templateExt");
                try {
                    if (templateExt != null) {
                        JSONObject jsonObject = new JSONObject(templateExt);
                        if (jsonObject.has("inputType")) {
                            String inputType = jsonObject.getString("inputType");
                            if ("checkbox".equals(inputType)) {
                                if (jsonObject.has("optionsStr")) {
                                    JSONArray optionsStr = jsonObject.getJSONArray("optionsStr");
                                    selectData.clear();
                                    for (int i = 0; i < optionsStr.length(); i++) {
                                        String string = optionsStr.getString(i);
                                        selectData.add(new SelectEntity(string, false));
                                    }
                                    selectAdapter.notifyDataSetChanged();
                                    conversationSelecte.setVisibility(View.VISIBLE);
                                    KeyboardUtils.closeKeybord(ConversationActivity.this);
                                    conversationInputView.setCanSendMsg(false);
                                }
                            } else if ("pic".equals(inputType)) {
                                convetsationUpload.setVisibility(View.VISIBLE);
                                conversationInputView.setCanSendMsg(false);
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        handler.post(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    boolean isLongtoTime(long messageTime) {
        long l = System.currentTimeMillis() - messageTime;
        if (getChatType() == EMMessage.ChatType.Chat) {
            if (entryData.getImChargesList().getChargesListStatus() != 2 || l > 90 * 1000) {
                return false;
            } else {
                return true;
            }
        } else if (getChatType() == EMMessage.ChatType.GroupChat) {
            if (entryGroupData.getImTeamChargesList() != null && !entryGroupData.getImTeamChargesList().isCanConsulting() || l > 90 * 1000) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前聊天类型
     */
    EMMessage.ChatType getChatType() {
        if (chatTypeStatus == 0) {
            return EMMessage.ChatType.Chat;
        } else if (chatTypeStatus == 1) {
            return EMMessage.ChatType.GroupChat;
        } else {
            return EMMessage.ChatType.ChatRoom;
        }
    }

    /**
     * 获取当前聊天对象
     */
    String getCurrentToAccount() {
        if (chatTypeStatus == 0) {
            return entryData.getDoctorImAccount();
        } else if (chatTypeStatus == 1) {
            return entryGroupData.getImTeamId();
        } else {
            return "";
        }
    }

    /**
     * 更换Url domin
     *
     * @param url
     * @return
     */
    String changeUrlVoide(String url) {
        ALog.e("changeUrlVoide", "changeUrlVoide: ---" + url);
//        https://easeim.yilijk.com/1103201016041605/yilijk/chatfiles/0baa14f0-2ca3-11ec-8c90-877a85828a24
        return url.replace("easeim.yilijk.com/1103201016041605/yilijk/chatfiles", "cdn-easeim.yilijk.com/5f21f35a-f896-481c-a167-fe2e825900d3");
    }

    /**
     * 判断消息是否是当前自己的消息
     */


    boolean isLeftMsg(String fromAccount) {
        String currentAccount = getCurrentToAccount();
        if (fromAccount.equals(currentAccount)) {
            return false;
        } else {
            return true;
        }
    }

    String getCurrentFromAccount() {
//        return SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imAccount, null);
        if (getChatType() == EMMessage.ChatType.Chat) {
            return entryData.getPatientImAccount();
        } else if (getChatType() == EMMessage.ChatType.GroupChat) {
            if (entryGroupData.getImTeamChargesList() != null && !TextUtils.isEmpty(entryGroupData.getImTeamChargesList().getPatientImAccount())) {
                return entryGroupData.getImTeamChargesList().getPatientImAccount();
            } else {
                return SharedPreferencesUtils.getInstance().getString(UserInfoConstants.imAccount, null);
            }
        } else {
            return entryData.getPatientImAccount();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
//        setInputText();
    }

    private void getInputText() {
        int chargesListid = 0;
        if (entryData != null && entryData.getImChargesList() != null && entryData.getImChargesList().getChargesListId() > 0) {
            chargesListid = entryData.getImChargesList().getChargesListId();
        } else {
            if (isInquiryRecord) {
                chargesListid = chargesListId;
            }
        }
        ALog.e("oakkkdb", "chargesListId start: " + chargesListid);
        String editStr = DataBaseUtil.getInstance().getData(this, DB_FN_CONVER_INPUT + chargesListid);
        if (!TextUtils.isEmpty(editStr)) {
            conversationInputView.setCurrentContent(editStr);
        }
//        if (conversationInputEt.getVisibility() == View.VISIBLE && chargesListid > 0) {
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        saveInputText();
    }

    private void saveInputText() {
        int chargesListid = 0;
        if (entryData != null && entryData.getImChargesList() != null && entryData.getImChargesList().getChargesListId() > 0) {
            chargesListid = entryData.getImChargesList().getChargesListId();
        } else {
            if (isInquiryRecord) {
                chargesListid = chargesListId;
            }
        }
        ALog.e("oakkkdb", "chargesListId stop: " + chargesListid);
        if (!TextUtils.isEmpty(conversationInputView.getCurrentContent())) {
            DataBaseUtil.getInstance().setData(this, DB_FN_CONVER_INPUT + chargesListid, conversationInputView.getCurrentContent());
        } else {
            DataBaseUtil.getInstance().removeData(this, DB_FN_CONVER_INPUT + chargesListid);
        }
//        if (conversationInputEt.getVisibility() == View.VISIBLE && chargesListid > 0) {
//        }
    }

    //消除未读
    public void openImChargeByChargeListId(int chargesListId) {
        RequestParams params = new RequestParams();
        params.put("chargesListId", chargesListId);
        HttpUtils.get(AllStringConstants.MessageUrl.openImChargeByChargeListId, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {


            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

    private void removeInputText() {
        int chargesListid = 0;
        if (entryData != null && entryData.getImChargesList() != null && entryData.getImChargesList().getChargesListId() > 0) {
            chargesListid = entryData.getImChargesList().getChargesListId();
        } else {
            if (isInquiryRecord) {
                chargesListid = chargesListId;
            }
        }
        ALog.e("oakkkdb", "chargesListId stop: " + chargesListid);
        DataBaseUtil.getInstance().removeData(this, DB_FN_CONVER_INPUT + chargesListid);
//        if (conversationInputEt.getVisibility() == View.VISIBLE && chargesListid > 0) {
//        }

    }

    private void disposeMsgTime(HbasePatientImManagerEntity.DataBean dataBean) {
        String sendTime = "";
        boolean showTime = false;
        long l = 0;
        long fiveMin = 5 * 60 * 1000;
        if (dataBean.getEmMessage() == null) {
            l = DataUtils.string2long(dataBean.getSendTime(), DataUtils.Type1);
            sendTime = dataBean.getSendTime();
        } else {
            l = dataBean.getEmMessage().getMsgTime();
            sendTime = DataUtils.long2string(dataBean.getEmMessage().getMsgTime(), DataUtils.Type1);
        }
        if (l - lastSendTime >= fiveMin || l - lastSendTime <= -fiveMin) {
            showTime = true;
        }
        //消息本身自带时间
        if (
                dataBean.getItemType() == 7002 ||
                        dataBean.getItemType() == 7004 ||
                        dataBean.getItemType() == 7006 ||
                        dataBean.getItemType() == 7011 ||
                        dataBean.getItemType() == 7012 ||
                        dataBean.getItemType() == 7021 ||
                        dataBean.getItemType() == 7022 ||
                        dataBean.getItemType() == 7023
        ) {
            showTime = true;
        }

        lastSendTime = l;
        dataBean.setShowTime(showTime);
        dataBean.setSendTime(sendTime);
    }

    void setShowInquiryEndHint(String chargeStatus) {
        //默认隐藏
        RequestParams params = new RequestParams();
        params.put("doctorPassportId", doctorPassportId);
        HttpUtils.get("/ihospital-patient/ipatient/doctor/queryDoctorWorkTab", params, new HttpCallBack<DoctorWorkTabEntity>() {
            @Override
            public void onSuccess(DoctorWorkTabEntity s, int i) {
                if (s.isResult()) {
                    inquirtHintView.setData(s.getData(), chargeStatus);
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecivedMessage(EventBusMessageWrap messageWrap) {
        ALog.e("onRecivedMessage");
        EMMessage message = messageWrap.message;
        switch (messageWrap.type) {
            case SendSuccess: {
                HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                dataBean.setEmMessage(message);
                conversationMessages.add(dataBean);
                if (message.getType() == EMMessage.Type.VOICE) {
                    //发送成功删除本地文件
                    EMVoiceMessageBody emVoiceMessageBody = (EMVoiceMessageBody) message.getBody();
                    String localUrl = emVoiceMessageBody.getLocalUrl();
                    File file = new File(localUrl);
                    if (file.exists()) {
                        file.delete();
                    }
                }

                if (getChatType() == EMMessage.ChatType.Chat){
                    //如果是随访 仅支持发送消息剩余条数查询
                    if (entryData.getImChargesList().getType() == 8) {
                        sf_canSendNum();
                    }
                }else{

                }
            }
            break;
            case MessageReceived: {
                if (message.getChatType() == EMMessage.ChatType.Chat
                        && TextUtils.equals(message.getFrom(), getCurrentToAccount())) {
                    HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                    dataBean.setEmMessage(message);
                    conversationMessages.removeIf(id -> TextUtils.equals(id.getMsgId(), message.getMsgId()));
                    conversationMessages.add(dataBean);
                } else if (message.getChatType() == EMMessage.ChatType.GroupChat
                        && TextUtils.equals(message.getTo(), entryGroupData.getImTeamId())) {
                    HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                    dataBean.setEmMessage(message);
                    conversationMessages.removeIf(id -> TextUtils.equals(id.getMsgId(), message.getMsgId()));
                    conversationMessages.add(dataBean);
                }
            }
            break;
            case MessageCmdReceived: {
                String from = message.getFrom();
                try {
                    List<EMMessage> data = EMClient.getInstance().chatManager().fetchHistoryMessages(from, EMConversation.EMConversationType.Chat, 2, null).getData();
                    for (int j = 0; j < data.size(); j++) {
                        HbasePatientImManagerEntity.DataBean dataBean = new HbasePatientImManagerEntity.DataBean();
                        if (data.get(j).getType() == EMMessage.Type.CUSTOM) {
                            dataBean.setEmMessage(data.get(j));
                            conversationMessages.add(dataBean);
                            EMCustomMessageBody body = (EMCustomMessageBody) data.get(j).getBody();
                        }
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
            break;
            case MessageRecalled: {
                String msgId = message.getMsgId();
                for (int i = 0; i < conversationMessages.size(); i++) {
                    String thisMessageId;
                    if (conversationMessages.get(i).getEmMessage() == null) {
                        thisMessageId = conversationMessages.get(i).getMsgId();
                    } else {
                        thisMessageId = conversationMessages.get(i).getEmMessage().getMsgId();
                    }
                    if (thisMessageId.equals(msgId)) {
                        conversationMessages.remove(i);
                        break;
                    }
                }
            }
            break;
            case IMLoginSuccess: {

            }
            break;
            case IMLoginError: {

            }
            break;
            case RefreshChat: {
                entryIm(false);
            }
            break;
            case RefreshChatGroup: {
                entryGroup(externalOrderNo);
            }
            break;
            case ClearMessageData: {
                conversationMessages.clear();
            }
            break;
            case NotifyData: {

            }
            break;
            case UnUseInput: {
//                conversationInputView.setCanSendMsg(false);
//                entryGroup(externalOrderNo);
            }
            break;
        }
        notifyDataSetChanged();
    }


    void sf_canSendNum() {
        RequestParams params = new RequestParams();
        params.put("chargesListId", entryData.getImChargesList().getChargesListId());
        HttpUtils.get(AllStringConstants.MessageUrl.residueDegreeAfterAnswer, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s, int i) {
                ALog.e(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.has("result") && jsonObject.getBoolean("result")) {
                        canSendMessageNo = jsonObject.getInt("data");
                        conversationInputView.setInputHint("剩余回复条数：" + canSendMessageNo);
                        if (canSendMessageNo == 0) {
                            conversationInputView.forbiddenInput(false);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String s, int i) {

            }
        });

    }




}